﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using DevExpress.Data;
using System.Linq;
using Frame.Global;
using System.Data.Linq;

namespace Frame.Pages
{
    public abstract class SimpleEditPage<T> : BasePage where T : class, new()
    {
        #region 数据操作相关对象 

        /// <summary>
        /// 窗口的sql语句
        /// </summary>
        public abstract string SInputQuerySQLString
        {
            get;
        }

        DataContext m_SInputDataSession = GlobalRunParms.GetDefaultDataContext();

        /// <summary>
        /// 数据集对像，留待实现类完成
        /// </summary>
        public  DataContext SInputDataSession
        {
            get
            {
                return m_SInputDataSession;
            }
        }
        /// <summary>
        /// 数据表集缓存变量
        /// </summary>
        List<T> m_DataList;
        /// <summary>
        /// 数据表集,虚属性可重写
        /// </summary>
        public virtual List<T> SInputDataTableList
        {
            get
            {

                if (Cache["m_DataList"] == null)
                {
                    if (!string.IsNullOrEmpty(SInputQuerySQLString))
                    {
                        Cache["m_DataList"] = SInputDataSession.ExecuteQuery<T>(SInputQuerySQLString, SInputSQLParams).Take(100000).ToList();
                    }
                    else
                    {
                        Cache["m_DataList"] = SInputDataSession.GetTable<T>().Take(100000).ToList();
                    }
                }
                return (List<T>)Cache["m_DataList"];
            }
        }

        /// <summary>
        /// 刷新数据，跟数据库保持一直
        /// </summary>
        public void Refresh()
        {
            SInputDataSession.Refresh(RefreshMode.OverwriteCurrentValues, SInputDataTableList);
        }

        #endregion

        #region 公共属性

        /// <summary>
        /// gridView的命令列
        /// </summary>
        public GridViewCommandColumn SInputCommandColumn
        {
            get
            {
                if (SInputIsAddCommandColumn)
                {
                    return gridView.Columns["inputcmdcol"] as GridViewCommandColumn;
                }
                else
                {
                    throw new Exception("没有添加Command列！");
                }
            }
        }

        string mGridSumColumn = "";
        /// <summary>
        /// 需要sum的列，多列之间用"|"分割
        /// </summary>
        public string SInputGridSumColumn
        {
            get { return mGridSumColumn; }
            set { mGridSumColumn = value; }
        }
        string mGridCountColumn = "";
        /// <summary>
        /// 需要count的列，多列之间用"|"分割
        /// </summary>
        public string SInputGridCountColunm
        {
            get { return mGridCountColumn; }
            set { mGridCountColumn = value; }
        }

        /// <summary>
        /// 设置主键列
        /// </summary>
        public abstract string SInputGridKeyColumn { get; }


        bool mIsAddCommandColumn = true;
        public bool SInputIsAddCommandColumn
        {
            get { return mIsAddCommandColumn; }
            set { mIsAddCommandColumn = value; }
        }
        bool mIsPopupEditForm = false;

        public bool SInputIsPopupEditForm
        {
            get { return mIsPopupEditForm; }
            set { mIsPopupEditForm = value; }
        }

        SqlParameter[] param;
        /// <summary>
        /// 数据检索参数
        /// </summary>
        public SqlParameter[] SInputSQLParams
        {
            get
            {
                return param;
            }
            set
            {
                param = value;
            }
        }
        #endregion


        #region 组件(Component)
        public ASPxGridView gridView;
        #endregion

        #region 事件
        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);


            gridView.CellEditorInitialize += new ASPxGridViewEditorEventHandler(gridView_CellEditorInitializeBase);
            gridView.RowDeleting += new DevExpress.Web.Data.ASPxDataDeletingEventHandler(gridView_RowDeletingBase);
            gridView.RowInserting += new DevExpress.Web.Data.ASPxDataInsertingEventHandler(gridView_RowInsertingBase);
            gridView.RowUpdating += new DevExpress.Web.Data.ASPxDataUpdatingEventHandler(gridView_RowUpdatingBase);


            gridView.SettingsBehavior.ConfirmDelete = true;
            try
            {
                    SQuerySetGridBeforeBind();
                    gridView.DataSource = SInputDataTableList;
                    gridView.DataBind();
                    //设置主键
                    gridView.KeyFieldName = SInputGridKeyColumn;
                    foreach (GridViewColumn item in gridView.Columns)//通过foreach例遍所有的Columns
                    {
                        if (item is GridViewDataComboBoxColumn)//当响应的columns为下拉框时设置文字显示为居中
                        {
                            item.CellStyle.HorizontalAlign = HorizontalAlign.Center;
                        }
                    }
                    (gridView.Columns[gridView.KeyFieldName] as GridViewDataTextColumn).EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.False;
                    if (!IsPostBack)
                    {
                        //处理合计列等一下脚信息
                        AddFootInfo();

                        if (mIsAddCommandColumn)
                        {
                            AddCommadColumn();
                        }

                        if (SInputIsPopupEditForm)
                        {
                            gridView.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm;
                            gridView.SettingsEditing.PopupEditFormModal = true;
                        }
                    }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 在GridView绑定数据之前对其进行设置
        /// 
        /// </summary>
        protected virtual void SQuerySetGridBeforeBind()
        {

        }
        #endregion

        #region 处理编辑区域的客户端实例


        #endregion

        #region 删除，修改保存数据
        /// <summary>
        /// 重新获取数据到uDataSet
        /// </summary>
        protected void SInputReQuery()
        {
            #region 重新取数据
            this.SInputDataSession.Refresh(RefreshMode.OverwriteCurrentValues, SInputDataTableList);
            gridView.DataSource = SInputDataTableList;
            gridView.DataBind();
            //设置主键
            gridView.KeyFieldName = SInputGridKeyColumn;
            #endregion
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void gridView_RowUpdatingBase(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            //在插入先的处理，需要自动增加列的数据等
            if (gridView_BeforeRowUpdating(e))
            {
                //DateTime begin1 = DateTime.Now;
                //T dataitem = new T();
                //for (int i = 0; i < 100000; i++)
                //{
                T dataitem = this.SInputDataTableList.Find(o =>
                    {
                        object obj=o.GetType().GetProperty(SInputGridKeyColumn).GetValue(o, null) ;
                        return obj.ToString() == e.OldValues[SInputGridKeyColumn].ToString();
                    });

                //}
                //DateTime end1 = DateTime.Now;
                //for (int i = 0; i < 100000; i++)
                //{
                    IDictionaryEnumerator enumerator = e.NewValues.GetEnumerator();
                    enumerator.Reset();
                    while (enumerator.MoveNext())
                    {
                        System.Reflection.PropertyInfo property =
                            dataitem.GetType().GetProperty(enumerator.Key.ToString());
                        property.SetValue(dataitem, enumerator.Value, null);
                    }
                //}
                //DateTime end2 = DateTime.Now;
                //throw new Exception(string.Format("查询总时间：{0}秒 , 设值总时间：{1}秒", end1.Subtract(begin1).TotalMilliseconds / 1000, end2.Subtract(end1).TotalMilliseconds / 1000));

                try
                {
                    this.SInputDataSession.SubmitChanges();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                gridView.CancelEdit();
                e.Cancel = true;
            }
            else
            {
                throw new Exception("更新失败！");
            }
            SInputReQuery();

        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void gridView_RowInsertingBase(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            if (gridView_BeforeRowInserting(e))
            {
                e.Cancel = true;

                T dataitem = new T();
                IDictionaryEnumerator enumerator = e.NewValues.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    System.Reflection.PropertyInfo property = 
                        dataitem.GetType().GetProperty(enumerator.Key.ToString());
                    property.SetValue(dataitem, enumerator.Value, null);
                }
                this.SInputDataSession.GetTable<T>().InsertOnSubmit(dataitem);
                try
                {
                    this.SInputDataSession.SubmitChanges();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                SInputReQuery();


                //如果有最大编号处理的，这里进行处理
                

                gridView.CancelEdit();
                e.Cancel = true;
                SInputReQuery();
                gridView.CancelEdit();
            }
            else
            {
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void gridView_RowDeletingBase(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            if (gridView_BeforeRowDeleting(e))
            {
                int i = gridView.FindVisibleIndexByKeyValue(e.Keys[gridView.KeyFieldName]);
                e.Cancel = true;

                T dataitem = this.SInputDataTableList.Find(o => 
                    o.GetType().GetProperty(SInputGridKeyColumn).GetValue(o, null) == e.Values[SInputGridKeyColumn]);
                this.SInputDataSession.GetTable<T>().DeleteOnSubmit(dataitem);
                try
                {
                    this.SInputDataSession.SubmitChanges();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                SInputReQuery();
            }
            else
            {
            }
        }
        #endregion

        #region 客户端代码

        /// <summary>
        /// 在更新前需要做的工作，返回值为bool，true 继续保存， false 放弃保存
        /// </summary>
        /// <param name="e">DevExpress.Web.Data.ASPxDataUpdatingEventArgs</param>
        /// <returns></returns>
        protected abstract bool gridView_BeforeRowUpdating(DevExpress.Web.Data.ASPxDataUpdatingEventArgs e);

        /// <summary>
        /// 在插入前需要做的工作，返回值为bool，true 继续保存， false 放弃保存
        /// </summary>
        /// <param name="e">DevExpress.Web.Data.ASPxDataUpdatingEventArgs</param>
        /// <returns></returns>
        protected abstract bool gridView_BeforeRowInserting(DevExpress.Web.Data.ASPxDataInsertingEventArgs e);

        /// <summary>
        /// 在删除前需要做的工作，返回值为bool，true 继续保存， false 放弃保存
        /// </summary>
        /// <param name="e">DevExpress.Web.Data.ASPxDataUpdatingEventArgs</param>
        /// <returns></returns>
        protected abstract bool gridView_BeforeRowDeleting(DevExpress.Web.Data.ASPxDataDeletingEventArgs e);

        #endregion

        #region 界面处理
        /// <summary>
        /// 界面处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void gridView_CellEditorInitializeBase(object sender, ASPxGridViewEditorEventArgs e)
        {
            e.Column.EditFormCaptionStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
            if (e.Column.Name.Substring(0, 2) == "t_")
                e.Editor.ClientInstanceName = "c_t_" + e.Column.FieldName;
            //设置下拉框初始值为SelectIndex=0
            if (e.Editor is ASPxComboBox)
            {
                (e.Editor as ASPxComboBox).ClientSideEvents.Init =
                    @"function(s,e){ if(s.GetSelectedIndex()==-1){s.SetSelectedIndex(0)} }";
            }
            //设置下拉式日期的初始值为当天
            if (e.Editor is ASPxDateEdit)
            {
                (e.Editor as ASPxDateEdit).Date = DateTime.Today;
            }
            //禁用所有下拉式控件的动态效果
            if (e.Editor is ASPxDropDownEdit)
            {
                (e.Editor as ASPxDropDownEdit).EnableAnimation = false;
            }

        }


        /// <summary>
        /// 按sqlstr获取下拉框的item
        /// </summary>
        /// <param name="gvc">下拉框列</param>
        /// <param name="strsql">获取item的sql</param>
        /// <param name="TextField">下拉框的text列映射值</param>
        /// <param name="ValueField">下拉框的value列映射值</param>
        protected void SQueryPolutateComboBoxColumn(string ColumnName, string strsql, string TextField, string ValueField)
        {
            GlobalFunctions.InitComboBoxColumn(gridView.Columns[ColumnName], strsql, TextField, ValueField);

        }
        /// <summary>
        /// 直接通过字符数组获取下拉框的item
        /// </summary>
        /// <param name="ColumnName">下拉框列列名</param>
        /// <param name="TextArray">显示的字符数组</param>
        /// <param name="ValueArray">值得字符数组</param>
        protected void SQueryPolutateComboBoxColumn(string ColumnName, string[] TextArray, string[] ValueArray)
        {
            GlobalFunctions.InitComboBoxColumn(gridView.Columns[ColumnName], TextArray, ValueArray);

        }

        /// <summary>
        /// 直接通过字符数组获取下拉框的item
        /// </summary>
        /// <param name="combobox">下拉框</param>
        /// <param name="TextArray">显示的字符数组</param>
        /// <param name="ValueArray">值得字符数组</param>
        protected void SQueryPolutateComboBox(ASPxComboBox combobox, string[] TextArray, string[] ValueArray)
        {
            GlobalFunctions.InitComboBox(combobox, TextArray, ValueArray);

        }
        /// <summary>
        /// 按sqlstr获取下拉框的item
        /// </summary>
        /// <param name="combobox">下拉框</param>
        /// <param name="strsql">获取item的sql</param>
        /// <param name="TextField">下拉框的text列映射值</param>
        /// <param name="ValueField">下拉框的value列映射值</param>
        protected void SQueryPolutateComboBox(ASPxComboBox combobox, string strsql, string TextField, string ValueField)
        {
            GlobalFunctions.InitComboBox(combobox, strsql, TextField, ValueField);

        }

        /// <summary>
        /// 在ASPxGrid内增加一个命令列
        /// </summary>
        private void AddCommadColumn()
        {

            //增加一个清理列
            GridViewCommandColumn commandColumn = new GridViewCommandColumn();
            commandColumn.Name = "inputcmdcol";
            commandColumn.ClearFilterButton.Visible = true;
            commandColumn.ClearFilterButton.Text = "清除过滤信息";
            commandColumn.ShowSelectCheckbox = false; ;
            commandColumn.EditButton.Visible = true;
            commandColumn.EditButton.Text = "编辑";

            commandColumn.DeleteButton.Visible = true;
            commandColumn.DeleteButton.Text = "删除";
            commandColumn.NewButton.Visible = true;
            commandColumn.NewButton.Text = "新增";
            commandColumn.UpdateButton.Visible = true;
            commandColumn.UpdateButton.Text = "更新";
            commandColumn.CancelButton.Visible = true;
            commandColumn.CancelButton.Text = "取消";
            commandColumn.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
            commandColumn.Caption = "操作";
            gridView.Columns.Add(commandColumn);

        }

        /// <summary>
        /// 在ASPxGird的最后增加合计和count信息
        /// </summary>
        private void AddFootInfo()
        {
            string mStrtmp = "";
            if (mGridSumColumn.Length > 0)
            {
                while (mGridSumColumn.Length > 0)
                {
                    mStrtmp = GlobalFunctions.f_GetToken(mGridSumColumn, "|", ref mGridSumColumn);
                    gridView.TotalSummary.Add(SummaryItemType.Sum, mStrtmp);
                }

            }

            if (mGridCountColumn.Length > 0)
            {
                while (mGridCountColumn.Length > 0)
                {
                    mStrtmp = GlobalFunctions.f_GetToken(mGridCountColumn, "|", ref mGridCountColumn);
                    gridView.TotalSummary.Add(SummaryItemType.Count, mStrtmp);
                }

            }
        }
        #endregion

    } 
}
